/**
 * Copyright (c) 2005-2012 https://github.com/zhangkaitao
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.aiwei.tdjk.serviceManager.serviceType.controller;


import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.common.entity.search.Searchable;
import com.aiwei.tdjk.common.web.bind.annotation.PageableDefaults;
import com.aiwei.tdjk.common.web.bind.annotation.SearchableDefaults;
import com.aiwei.tdjk.common.web.controller.BaseCRUDController;
import com.aiwei.tdjk.common.web.validate.ValidateResponse;
import com.aiwei.tdjk.serviceManager.serviceType.entity.ServiceType;
import com.aiwei.tdjk.serviceManager.serviceType.service.ServiceTypeService;
import com.aiwei.tdjk.sys.user.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;


@Controller
@RequestMapping(value = "/admin/serviceManager/serviceType")
public class ServiceTypeController extends BaseCRUDController<ServiceType, Long> {

    private ServiceTypeService getServiceTypeService() {
        return (ServiceTypeService) baseService;
    }

    public ServiceTypeController() {
        setResourceIdentity("serviceManager:serviceType");
    }

    @Override
    protected void setCommonData(Model model) {

    }

    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    @PageableDefaults(sort = "id=desc")
    @SearchableDefaults(value = "deleted_eq=0")
    public String listAll(Searchable searchable, Model model) {
        return list(searchable, model);
    }



    @RequestMapping(value = "create/discard", method = RequestMethod.POST)
    @Override
    public String create(
            Model model, @Valid @ModelAttribute("m") ServiceType m, BindingResult result,
            RedirectAttributes redirectAttributes) {
        throw new RuntimeException("discarded method");
    }

    @RequestMapping(value = "{id}/update/discard", method = RequestMethod.POST)
    @Override
    public String update(
            Model model, @Valid @ModelAttribute("m") ServiceType m, BindingResult result,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {
        throw new RuntimeException("discarded method");
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String createWithOrganization(
            Model model,
            @Valid @ModelAttribute("m") ServiceType m, BindingResult result,
            @RequestParam(value = "organizationId", required = false) Long[] organizationIds,
            @RequestParam(value = "jobId", required = false) Long[][] jobIds,
            RedirectAttributes redirectAttributes) {


        return super.create(model, m, result, redirectAttributes);
    }



    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    public String updateWithOrganization(
            Model model, @Valid @ModelAttribute("m") ServiceType m, BindingResult result,
            @RequestParam(value = "organizationId", required = false) Long[] organizationIds,
            @RequestParam(value = "jobId", required = false) Long[][] jobIds,
            @RequestParam(value = Constants.BACK_URL, required = false) String backURL,
            RedirectAttributes redirectAttributes) {


        return super.update(model, m, result, backURL, redirectAttributes);
    }




    @RequestMapping(value = "recycle")
    public String recycle(HttpServletRequest request, @RequestParam("ids") Long[] ids, RedirectAttributes redirectAttributes) {
        for (Long id : ids) {
            ServiceType serviceType = getServiceTypeService().findOne(id);
            serviceType.setDeleted(Boolean.FALSE);
            getServiceTypeService().update(serviceType);
        }
        redirectAttributes.addFlashAttribute(Constants.MESSAGE, "还原成功！");
        return redirectToUrl((String) request.getAttribute(Constants.BACK_URL));
    }


    @RequestMapping("{user}/organizations")
    public String permissions(@PathVariable("user") User user) {
        return viewName("organizationsTable");
    }





    /**
     * 验证返回格式
     * 单个：[fieldId, 1|0, msg]
     * 多个：[[fieldId, 1|0, msg],[fieldId, 1|0, msg]]
     *
     * @param fieldId
     * @param fieldValue
     * @return
     */
    @RequestMapping(value = "validate", method = RequestMethod.GET)
    @ResponseBody
    public Object validate(
            @RequestParam("fieldId") String fieldId, @RequestParam("fieldValue") String fieldValue,
            @RequestParam(value = "id", required = false) Long id) {

        ValidateResponse response = ValidateResponse.newInstance();


        if ("username".equals(fieldId)) {
            ServiceType serviceType = getServiceTypeService().findByName(fieldValue);
            if (serviceType == null || (serviceType.getId().equals(id) && serviceType.getName().equals(fieldValue))) {
                //如果msg 不为空 将弹出提示框
                response.validateSuccess(fieldId, "");
            } else {
                response.validateFail(fieldId, "用户名已被其他人使用");
            }
        }

        return response.result();
    }


}
